package com.qili.core.quartz.CustomQuartz;

import cn.hutool.core.util.IdUtil;
import com.qili.core.utils.DictTypes;
import com.qili.entity.base.BaseDict;
import com.qili.entity.supervisor.ProjectNotice;
import com.qili.entity.supplier.SupplierProject;
import com.qili.entity.supplier.SupplierProjectAccept;
import com.qili.entity.supplier.dto.SupplierProjectAcceptDTO;
import com.qili.entity.supplier.dto.SupplierProjectDTO;
import com.qili.entity.sys.SysUser;
import com.qili.entity.sys.dto.SysUserDTO;
import com.qili.redis.RedisService;
import com.qili.service.SysUserService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.supervisor.ProjectNoticeServie;
import com.qili.service.supplier.RecommendReasonService;
import com.qili.service.supplier.SupplierProjectAcceptService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.service.supplier.SupplierProjectPubNoticeService;
import com.qili.util.DateUtil;
import com.qili.util.StringUtil;
import lombok.extern.java.Log;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaoyongke 每天执行一次 //内部项目，X日后自动进行第二次比价，最多进行三次比
 * @date 2021/4/7
 * @description
 */
@Log
public class NbYjNoticeJob implements Job {
    @Autowired
    SysUserService sys;
    @Autowired
    private SupplierProjectPubNoticeService supplierProjectPubNoticeService;
    @Autowired
    private SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    ProjectNoticeServie projectNoticeServie;
    @Autowired
    SupplierProjectAcceptService supplierProjectAcceptService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    BaseCompanyService baseCompanyService;
    @Autowired
    private RecommendReasonService recommendReasonService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("NbYjNoticeJob：启动任务=======================");
        run();
        System.out.println("NbYjNoticeJob：下次执行时间=====" +
                new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                        .format(context.getNextFireTime()) + "==============");
    }

    public void run() {

        log.info("NbYjNoticeJob=======开始==================================");
        String lockkey = "NbYjNoticeJob_key";
        String uuId = IdUtil.simpleUUID();
        try {
            lock(lockkey, uuId);
            //内部项目，X日后自动进行第二次比价，最多进行三次比
            saveSendXfZbjzRiqi();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            unlock(lockkey, uuId);
        }
    }

    /**
     * @param
     * @Author:zhaoyongke
     * @Description:设置X日后不响应则自动默认之前的费用 或X日后自动进行第二次比价，
     * @Date:16:09 2021/4/12
     */
    public void saveSendXfZbjzRiqi() {

        try {
            // 设置X日后不响应则自动默认之前的费用 或X日后自动进行第二次比价，
            List<BaseDict> typeListSsbl = baseDictService.selectByTypeCode(DictTypes.NBXT001.getType());
            String xvalue = "";
            if (typeListSsbl.size() > 0) {
                BaseDict bzjbl = typeListSsbl.get(0);
                xvalue = bzjbl.getBadtLevel1();
            }
            // 查询议价中的项目
  /*          Example e = new Example(SupplierProject.class);
            Example.Criteria c = e.createCriteria();
            c.andEqualTo("status", "006");
            c.andEqualTo("publishType", "001");
            c.andEqualTo("yjStatus", "1");
            //没有推荐中标人的项目
            c.andEqualTo("tjStatus", "0");
            List<SupplierProject> supplierProjects = supplierProjectManagerService.selectByExample(e);*/

            SupplierProjectDTO dtopro = new SupplierProjectDTO();
            dtopro.setStatus("006");
            dtopro.setPublishType("001");
            dtopro.setYjStatus("1");
            dtopro.setTjStatusNo("0");
            List<SupplierProjectDTO> supplierProjects = supplierProjectManagerService.selectProject(dtopro);
            System.out.println("11");
            for (int i = 0; i < supplierProjects.size(); i++) {
                System.out.println("12");
                SupplierProject project = supplierProjects.get(i);
                String zbDate = project.getZbEndDate();
                Date zbEndDate = DateUtil.parseDate(zbDate, "yyyy-MM-dd HH:mm");
                String jyDateStr = project.getYjDate();
                // 上次议价，x天之后的日期
                Date jyDate = DateUtil.parseDate(jyDateStr, "yyyy-MM-dd HH:mm");
                Double x = Double.valueOf(xvalue) * 24;
                int i2 = x.intValue();
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(jyDate);
                calendar.add(Calendar.HOUR, i2);
                /*招标截止是时间x天之前 */
                Date dateafter = new Date(calendar.getTimeInMillis());

                Date currdate = new Date();
                //
                System.out.println("13");
                if (currdate.after(zbEndDate) && currdate.after(dateafter)) {
                    System.out.println("14");
                    Boolean isyj = false;
                    // 到了 招标截止时间
                    SupplierProjectAcceptDTO acceptDTO = new SupplierProjectAcceptDTO();
                    acceptDTO.setSupProjectId(project.getSupProjectId());
                    acceptDTO.setScoreDesc("desc");
                    List<SupplierProjectAcceptDTO> acceptlist = supplierProjectAcceptService.selectListByScore(acceptDTO);
                    if (acceptlist.size() == 1) {
                        System.out.println("15");
                        // 有一人应接的情况   推荐中标
                        ProjectNotice notice = new ProjectNotice();
                        notice.setLinkId(project.getSupProjectId());
                        notice.setNoticeType("107");
                        int y1 = projectNoticeServie.selectCount(notice);
                        if (y1 == 0) {
                            sendNoticeToXfTjzb(project, acceptlist.get(0));
                        }
                        project.setTjStatus("1");// 结束
                        project.setTjPerson(acceptlist.get(0).getAcceptBy());
                        project.setTjDate(DateUtil.getCurrentDateString("yyyy-MM-dd HH:mm"));
                        supplierProjectManagerService.updateByPrimaryKey(project);

                    } else if (acceptlist.size() > 1) {
                        System.out.println("16");
                        //有最低价选择最低价  推荐中标
                        SupplierProjectAcceptDTO dto = new SupplierProjectAcceptDTO();
                        dto.setSupProjectId(project.getSupProjectId());
                        List<SupplierProjectAcceptDTO> supplierProjectAcceptDTOS = supplierProjectAcceptService.selectAcceptByScore(dto);
                        SupplierProjectAcceptDTO acceptDTO1 = supplierProjectAcceptDTOS.get(0);
                        String num = acceptDTO1.getNum();
                        if ("1".equals(num)) {
                            System.out.println("17");
                            //推荐最低价
                            String totalMoney = acceptDTO1.getTotalMoney();
                            SupplierProjectAccept accpet = new SupplierProjectAccept();
                            accpet.setSupProjectId(project.getSupProjectId());
                            accpet.setTotalMoney(totalMoney);
                            List<SupplierProjectAccept> select = supplierProjectAcceptService.select(accpet);
                            if (select.size() > 0) {
                                System.out.println("18");
                                ProjectNotice notice = new ProjectNotice();
                                notice.setLinkId(project.getSupProjectId());
                                notice.setNoticeType("107");
                                int y1 = projectNoticeServie.selectCount(notice);
                                if (y1 == 0) {
                                    System.out.println("19");
                                    SupplierProjectAccept accept = select.get(0);
                                    sendNoticeToXfTjzb(project, accept);
                                    project.setTjPerson(accept.getAcceptBy());
                                }
                            }
                            project.setTjStatus("1");// 结束
                            project.setTjDate(DateUtil.getCurrentDateString("yyyy-MM-dd HH:mm"));
                            supplierProjectManagerService.updateByPrimaryKey(project);
                        } else {
                            System.out.println("20");
                            //如果有多家相同的最低价，则给最低价的应接人发送议价通知
                            Integer yjnum = project.getYjNum();
                            // 最多比价三次
                            if (yjnum < 1) {
                                System.out.println("21");
                                String totalMoney = acceptDTO1.getTotalMoney();
                                // 2021 0908 给所有应接 发送 议价 通知
                                SupplierProjectAcceptDTO fjydto = new SupplierProjectAcceptDTO();
                                //fjydto.setTotalMoney(totalMoney);
                                fjydto.setSupProjectId(project.getSupProjectId());
                                List<SupplierProjectAccept> select = supplierProjectAcceptService.select(fjydto);
                                ArrayList<String> jypersonlist = new ArrayList<>();
                                for (int j = 0; j < select.size(); j++) {
                                    System.out.println("22");
                                    SupplierProjectAccept accept = select.get(j);
                                    // 发送议价通知
                                    supplierProjectManagerService.sendNoticeToYj(project, accept, "second定时器生成议价");
                                    isyj = true;
                                    jypersonlist.add(accept.getAcceptBy());
                                }
                                if (isyj) {
                                    System.out.println("23");
                                    String jypersonliststr = jypersonlist.toString();
                                    String yjperson = "";
                                    if (StringUtil.isNotBlank(jypersonliststr)) {
                                        //截取前后【】
                                        yjperson = jypersonliststr.replaceAll("\\[", "").replaceAll("\\]", "");
                                    }
                                    project.setYjPerson(yjperson);
                                }
                            } else {
                                System.out.println("24");
                                //如果还是有相同的则系统自动推荐应接人中综合评分排行第一的为中标人
                                // 调用综合对比方法（以防止 没有比分之前调用）
                                // 根据综合推荐结果来推荐
                                recommendReasonService.insertComparison(project.getSupProjectId());
                                SupplierProjectAcceptDTO scoredto = new SupplierProjectAcceptDTO();
                                scoredto.setSupProjectId(project.getSupProjectId());
                                scoredto.setAcceptOrder("333");
                                List<SupplierProjectAcceptDTO> supplierProjectAcceptDTOS1 = supplierProjectAcceptService.selectListByScore(scoredto);
                                if (supplierProjectAcceptDTOS1.size() > 0) {
                                    SupplierProjectAcceptDTO acceptDTO2 = supplierProjectAcceptDTOS1.get(0);
                                    ProjectNotice notice = new ProjectNotice();
                                    notice.setLinkId(project.getSupProjectId());
                                    notice.setNoticeType("107");
                                    int y1 = projectNoticeServie.selectCount(notice);
                                    if (y1 == 0) {
                                        System.out.println("25");
                                        sendNoticeToXfTjzb(project, acceptDTO2);
                                        project.setTjPerson(acceptDTO2.getAcceptBy());
                                    }
                                    System.out.println("26");
                                    project.setTjStatus("1");// 结束
                                    project.setTjDate(DateUtil.getCurrentDateString("yyyy-MM-dd HH:mm"));
                                    supplierProjectManagerService.updateByPrimaryKey(project);
                                }
                            }
                        }

                    }
                    if (isyj) {
                        System.out.println("27");
                        project.setYjStatus("1");
                        project.setYjNum(project.getYjNum() + 1);
                        project.setYjDate(DateUtil.getCurrentDateString("yyyy-MM-dd HH:mm"));
                        supplierProjectManagerService.updateByPrimaryKey(project);
                    }
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }


    }


    /**
     * @param project
     * @Author:zhaoyongke
     * @Description:
     * @Date:15:45 2021/4/12
     */
    public void sendNoticeToXfTjzb(SupplierProject project, SupplierProjectAccept accept) throws Exception {

        // 系统推荐出项目中标人后推送消息给 【中标审核人】角色 zbCheckPerson
        SysUserDTO sysUserDTO = new SysUserDTO();
        sysUserDTO.setUserRole("zbCheckPerson");
        List<SysUser> sysUsers = sysUserService.getUserDicts(sysUserDTO);
        for (int i = 0; i < sysUsers.size(); i++) {
            String acceptBy = accept.getAcceptBy();
            SysUser sysUser = sysUserService.selectByPrimaryKey(acceptBy);
            String personType = sysUser.getPersonType();
            String realName = "";
            if ("001".equals(personType)) {
                // 个人
                realName = sysUser.getRealName();
            } else {
                realName = sysUser.getLinkPerson();
            }
            ProjectNotice notice = new ProjectNotice();
            notice.setLinkId(project.getSupProjectId());
            notice.setIsView("0");
            notice.setSendTo(sysUsers.get(i).getId());
            notice.setTitle(project.getProjectName() + "项目推荐中标人为" + realName + "，请确认是否同意");
            notice.setNoticeType("107");// 内部单位推荐
            notice.setApplicantType("002");// 供需
            notice.setContent(project.getProjectName());
            notice.setCreateDate(DateUtil.getCurrentDateString());
            notice.setTjPerson(acceptBy);
            notice.setRemark("second定时任务生成");
            projectNoticeServie.insertSelective(notice);
        }

    }

    public void lock(String key, String uuId) {
        for (; ; ) {

            System.out.println(redisService);
            boolean r = stringRedisTemplate.opsForValue().setIfAbsent(key, uuId);
            stringRedisTemplate.expire(key, 600, TimeUnit.SECONDS);

            if (r) {
                return;
            } else {
                throw new RuntimeException("已经存在的执行程序...");
            }
        }
    }

    public void unlock(String key, String uuId) {
        if (uuId.equals(stringRedisTemplate.opsForValue().get(key))) {
            stringRedisTemplate.delete(key);
        }
    }

}
